<template>
  <ZZDialog class="form-context" title="图层配置">
    <el-form :model="form" ref="mySelf" label-width="80px" class="main-form" :rules="formRules">
      <el-form-item label="图层名称" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>

      <el-form-item label="URL" prop="url">
        <el-input v-model="form.url" />
      </el-form-item>

      <el-form-item label="ID" prop="id">
        <el-input v-model="form.id" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onAdd(mySelf)">创建</el-button>
      </el-form-item>
    </el-form>
  </ZZDialog>
</template>

<script setup>
import ZZDialog from '@/common/ZZDialog.vue';
import { reactive, toRaw, ref, onBeforeMount } from 'vue';
import { useViewer } from '@/stores/viewer';
import EventBus from '@/common/EventBus';

const emits = defineEmits(['ok']);
const viewer = useViewer().viewer;
const mySelf = ref(null);

const form = reactive({
  type: 'geojson',
  url: './data/layer/Export_Output_4.json',
  name: 'GeoJson矢量',
  id: Cesium.createGuid(),
  visible: true
});

// 表单验证规则
const formRules = {
  url: [
    {
      required: true,
      message: '请输入url',
      trigger: 'blur'
    }
  ],
  name: [
    {
      required: true,
      message: '请输入图层名称',
      trigger: 'blur'
    }
  ]
};

async function onAdd(formEl) {
  try {
    // 表单验证
    await mySelf.value.validate();

    const config = Object.assign({}, toRaw(form));
    const layer = zz3d.layer.createLayer(config, viewer);
    //绑定到图层管理中
    viewer.zz.addOperationalLayer(layer);
    EventBus.emit('sceneLoaded', {});
    emits('ok', {});
  } catch (error) {
    console.error('配置不正确:', error);
    ElMessage.error('请检查输入信息');
  }
}
</script>

<style scoped>
.text-right {
  text-align: right;
  padding-right: 5px;
  width: 26px;
}

.form-context {
  position: absolute;
  /* 垂直方向居中起点 */
  top: 50%;
  /* 水平方向居中起点 */
  left: 50%;
  /* 调整自身位置到正中心 */
  transform: translate(-50%, -50%);
}

.main-form {
  margin-top: 10px;
  margin-bottom: 16px;
}
</style>
